<template>
    <div class="mainDiv" style="padding:0px 15px; box-sizing: border-box;">
        <el-collapse style="height: 100%; overflow-y: auto; overflow-x: hidden;" :value="atv">
            <el-collapse-item :name="r.id" v-for="(r,index) in rule" :key="index">
                <el-checkbox slot="title" @change="checkAll(r)" v-model="r.checked">{{r.name}}</el-checkbox>
                <el-checkbox v-for="(c,index) in r.child" v-model="c.checked" @change="checkBufen(r)" :key="index">{{c.name}}</el-checkbox>
            </el-collapse-item>
        </el-collapse>
        <el-row class="rowHead">
            <el-button style="float: right" class="fr" size="mini" type="danger" icon="el-icon-close" @click="closeWin">取消</el-button>
            <el-button style="float: right;margin-right:10px;" class="fr" size="mini" type="success" icon="el-icon-upload2" @click="submit">确定</el-button>
        </el-row>
    </div>
</template>
<script>
import C from '@/common/common.js'
export default {
  name: 'editGuest',
  data () {
    return {
      rule: [],
      permission: [],
      atv: []
    }
  },
  methods: {
    getlimit: async function () {
      var that = this
      let data = await C.ajax('/shop/rule/getrule', { id: C.getDatas().id })
      if (data) {
        let perm = data.permission == '' ? '' : JSON.parse(data.permission)

        let rList = []
        data.rule.forEach((v) => {
          if (v.category === 5) {
            v.checked = true
            v.child = []
            rList.push(v)
            that.atv.push(v.id)
          }
        })

        data.rule.forEach((v) => {
          if (v.category === 6) {
            rList.forEach((r) => {
              if (v.pid == r.id) {
                if (perm.indexOf(v.tags) != -1) v.checked = true
                else v.checked = false
                r.child.push(v)
                if (!v.checked) r.checked = false
              }
            })
          }
        })

        that.rule = rList
        that.permission = perm
      }
    },
    checkAll: function (o) {
      if (o.checked) {
        o.child.forEach((v) => {
          v.checked = true
        })
      } else {
        o.child.forEach((v) => {
          v.checked = false
        })
      }
    },
    checkBufen: function (o) {
      o.child.forEach((v) => {
        if (!v.checked) o.checked = false
      })
    },
    submit: async function () {
      let permis = []
      this.rule.forEach((v) => {
        v.child.forEach((c) => {
          if (c.checked) {
            permis.push(c.tags)
          }
        })
      })

      let rtData = {
        pers: JSON.stringify(permis),
        id: C.getDatas().id
      }
      let data = await C.ajax('/shop/rule/editadminpermissions', rtData, 'post')
      if (data) {
        C.closeBrowserWindow(data)
      }
    },
    closeWin: function () {
      C.closewin()
    }
  },
  mounted: function () {
    this.getlimit()
  }
}
</script>